package encryption
import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
)

//AES加密函数
func Padding(plainText []byte,blockSize int) []byte{
	n:= blockSize-len(plainText)%blockSize
	temp:=bytes.Repeat([]byte{byte(n)},n)
	plainText=append(plainText,temp...)
	return plainText
}
//对密文删除填充
func UnPadding(cipherText []byte) []byte{
	end:=cipherText[len(cipherText)-1]
	cipherText=cipherText[:len(cipherText)-int(end)]
	return cipherText
}
//AEC加密（CBC模式）
func AES_CBC_Encrypt(plainText []byte,key []byte) []byte{
	block,err:=aes.NewCipher(key)
	if err!=nil{
		panic(err)
	}
	plainText=Padding(plainText,block.BlockSize())
	iv:=[]byte("12345678abcdefgh")
	blockMode:=cipher.NewCBCEncrypter(block,iv)
	cipherText:=make([]byte,len(plainText))
	blockMode.CryptBlocks(cipherText,plainText)
	//返回密文
	return cipherText
}
//AEC解密（CBC模式）
func AES_CBC_Decrypt(cipherText []byte,key []byte) []byte{
	block,err:=aes.NewCipher(key)
	if err!=nil{
		panic(err)
	}
	iv:=[]byte("12345678abcdefgh")
	blockMode:=cipher.NewCBCDecrypter(block,iv)
	//解密
	plainText:=make([]byte,len(cipherText))
	blockMode.CryptBlocks(plainText,cipherText)
	//plainText=UnPadding(plainText)
	return plainText
}

func crptoFunc(input string) (output string){
	message:=[]byte("Hello!My name is X.")
	key:=[]byte("abcdefgh98765432")
	cipherText:=AES_CBC_Encrypt(message,key)
	return string(cipherText)
}

func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
	cipher, _ := aes.NewCipher(generateKey(key))
	length := (len(origData) + aes.BlockSize) / aes.BlockSize
	plain := make([]byte, length*aes.BlockSize)
	copy(plain, origData)
	pad := byte(len(plain) - len(origData))
	for i := len(origData); i < len(plain); i++ {
		plain[i] = pad
	}
	encrypted = make([]byte, len(plain))
	// 分组分块加密
	for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Encrypt(encrypted[bs:be], plain[bs:be])
	}

	return encrypted
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
	cipher, _ := aes.NewCipher(generateKey(key))
	decrypted = make([]byte, len(encrypted))
	//
	for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}

	return decrypted[:trim]
}
func generateKey(key []byte) (genKey []byte) {
	genKey = make([]byte, 16)
	copy(genKey, key)
	for i := 16; i < len(key); {
		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
			genKey[j] ^= key[i]
		}
	}
	return genKey
}